const router = require('koa-router')()
const { userRegister, userLogin } = require('../controller/user')
const { SucceedMess, ErrMess } = require('../res-message/index')

router.prefix('/api/user')

// 注册接口
router.post('/register', async (ctx, next) => {
  const { username, password } = ctx.request.body // 获取请求

  try{
    const newUser = await userRegister(username, password) // 创建用户数据库
    ctx.body = new SucceedMess(newUser)

  }catch(e){ // 捕获错误
    console.error(e) // 打印错误
    ctx.body = new ErrMess(10001, `注册失败--${e.message}`)
  }
})

// 登录接口
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body // 获取请求
  const isLogin = await userLogin(username, password)
  if(isLogin){
    ctx.session.userInfo = { username }
    ctx.cookies.set('isLogin', true, {
      path:'/',
      httpOnly:false,
      maxAge:24 * 60 * 60 * 1000
    })
    ctx.body = new SucceedMess(isLogin)
  }else {
    ctx.body = new ErrMess(10002, `登录失败`)
  }
})

module.exports = router
